<?php

abstract class OOWP_Formattable
    extends OOWP_Base
{

    public function __construct(array $args = array( ))
    {
        $input = array_merge(array(
            'parent' => null,
        ), $args);

        parent::__construct($input);
    } // __construct

    /* ACCESSORS */

    abstract protected function getFormatPieces( );

    protected function getParent( )
    {
        return $this->dict['parent'];
    } // getParent

    protected function getGovernor( )
    {
        $governor = $this->parent;
        if (is_null($this->parent)) { echo '<p>NULL</p>'; }
        while(!is_null($governor)) {
            if ($governor instanceof OOWP_Element_Article) {
                return $governor;
            } else {
                $governor = $governor->parent;
            }
        }
        return $governor;
    } // getGovernor

    protected function setParent($value)
    {
        if ($value instanceof OOWP_Formattable) {
            $this->dict['parent'] = $value;
        } elseif (is_null($value)) {
            $this->dict['parent'] = null;
        }
    } // setParent

    /* METHODS */

    public function format( ) {
        $pieces = $this->format_pieces;
        if (method_exists($this, 'filter_format_pieces')) {
            $pieces = $this->filter_format_pieces($pieces);
        }
        if (!is_array($pieces)) {
            throw new Exception('Format pieces must be an array.');
        }
        return $pieces;
    } // format

    protected function collect_format_pieces($input, $indented = false) {
        $result = array( );
        $indent = '';

        if ($indented) {
            $indent = "\t";
        }

        if ($input instanceof OOWP_Formattable) {
            $input = array($input);
        }

        if (count($input)) {
            foreach ($input as $contribution) {
                if (is_string($contribution)) {
                    $result[ ] = "$indent$contribution";
                } elseif ($contribution instanceof OOWP_Formattable) {
                    $format = $contribution->format( );
                    foreach ($format as $line) {
                        $result[ ] = "$indent$line";
                    }
                }
            }
        }

        return $result;
    } // collect_format_pieces

}
